$(function () {
    var isWechat = function () {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        }
        return false;
    }
    var isAndroid = function () {
        var u = navigator.userAgent.toLowerCase();
        if (u.indexOf('android') > -1 || u.indexOf('linux') > -1) {
            return true;
        }
        return false;
    }
    $('.backByHash').click(function () {
        var backUrl = $(this).attr('back-url');
        var hash = location.hash.replace('#', '');
        if (backUrl && hash && isAndroid()) {
            var hs = hash.split('_');
            if (hs.length === 5) {
                location.href = backUrl + '?offset=' + (hs[1] || 0) + '&go=' + hs[2] + '&catIds=' + hs[3] + '&sort=' + hs[4] + '#' + hs[0];
                return;
            }
        }
        history.back();
    });
    if (isAndroid()) {
        $('body').on('click', '.browse-item .goods-item', function () {
            var self = $(this);
            var href = self.attr('href');
            var hash = location.hash.replace('#', '');
            var offset = self.attr('offset');
            var itemId = self.attr('item-id');
            var catIds = $('.pinp-navul a.active').attr('data-value');
            var sort = $('.order-wrapper a.active').attr('data-value');

            location.href = href + '#' + hash + '_' + offset + '_' + itemId + '_' + catIds + '_' + sort;
            return false;
        });
    }
    var getQueryString = function (url, name) {
        url = url.split('#')[0];
        var reg = new RegExp("[\?|\&]" + name + "=([^&]*)(&|$)", "i");
        var r = url.match(reg);
        if (r != null) return r[1];
        return null;
    }
    $('body').on('click', '.popcoupon', function () {
        var self = $(this);
        $.showLoading();
        $.get('/section/popcoupon', {
            activityId: self.attr('activityId'),
            pid: self.attr('pid'),
            itemId: self.attr('itemId'),
            quan_amount: self.attr('quan_amount'),
            isWechat: isWechat() ? 1 : 0
        }).then(function (html) {
            $('body').append(html);

            var clipboard = new Clipboard('#copybtn', {
                text: function (trigger) {
                    return $('#copybox').val();
                }
            });
            clipboard.on('success', function (e) {
                e.clearSelection();

                $('.popw').remove();
                clipboard.destroy();
                return $.toptip('复制成功', 'success');
            });
            clipboard.on('error', function (e) {
                $('#copybtn').removeClass('weui_btn_warn').addClass('weui_btn_default');
                $('#copybtn').text('请手动复制')

                return $.toptip('复制失败, 请手动全选广本复制', 'error');
            });

            $('.popwbg').click(function () {
                $('.popw').remove();
                clipboard.destroy();
            });
        }).always(function () {
            $.hideLoading();
        });
    });

    var taoke = {
        initLogin: function () {
            $('#login_btn').click(function () {
                return $.ajax({
                    type: 'POST',
                    url: '/api/public/v1/user/login',
                    data: $('#login_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '登录失败', 'error');
                    }
                    location.href = '/user_center';
                });
            });
        },

        initRegister: function () {
            var sendBtn = $('#send_btn');
            var timeCount = $('#time_count');
            var countValue = $('#count_value');

            $('#send_btn').click(function () {
                $.post('/api/public/v1/user/send_code', {
                    type: 'register',
                    tel: $('#tel').val()
                }, function (result) {
                    if (result.success) {
                        sendBtn.hide();
                        timeCount.show();

                        countValue.html('59');
                        var timer = setInterval(function () {
                            var time = parseInt(countValue.html());
                            if (time) {
                                countValue.html(time - 1);
                            } else {
                                clearInterval(timer);

                                sendBtn.show();
                                timeCount.hide();
                            }
                        }, 1000);

                        return $.toptip('验证码发送成功', 'success');
                    } else {
                        return $.toptip(result.message || '验证码发送失败', 'error');
                    }
                }, 'json');
            });

            $('#register_btn').click(function () {
                return $.ajax({
                    type: 'POST',
                    url: '/api/public/v1/user/register',
                    data: $('#register_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '注册失败', 'error');
                    }
                    location.href = '/user_center';
                });
            });
        },

        initForgot: function () {
            var sendBtn = $('#send_btn');
            var timeCount = $('#time_count');
            var countValue = $('#count_value');

            $('#send_btn').click(function () {
                $.post('/api/public/v1/user/send_code', {
                    type: 'forgot',
                    tel: $('#tel').val()
                }, function (result) {
                    if (result.success) {
                        sendBtn.hide();
                        timeCount.show();

                        countValue.html('59');
                        var timer = setInterval(function () {
                            var time = parseInt(countValue.html());
                            if (time) {
                                countValue.html(time - 1);
                            } else {
                                clearInterval(timer);

                                sendBtn.show();
                                timeCount.hide();
                            }
                        }, 1000);

                        return $.toptip('验证码发送成功', 'success');
                    } else {
                        return $.toptip(result.message || '验证码发送失败', 'error');
                    }
                }, 'json');
            });

            $('#forgot_btn').click(function () {
                return $.ajax({
                    type: 'POST',
                    url: '/api/public/v1/user/forgot',
                    data: $('#forgot_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '重置失败', 'error');
                    }
                    return $.toptip('重置成功', 'success');
                });
            });
        },

        initDetail: function () {
            var goods_id = $('#goods_id').val();
            var seller_id = $('#seller_id').val();
            var title = $('#title').val();
            var goods_url = $('#goods_url').val();

            /**
             * 价格走势
             */
            $.ajax({
                type: "GET",
                cache: true,
                url: '/section/price_trend?url=' + goods_url,
                dataType: "html",
                success: function (html) {
                    $('#priceTrend').html(html);

                    var ctx = document.getElementById('priceChart').getContext('2d');
                    var chart = new Chart(ctx, chatData);
                }
            });

            /**
             * 同店商品
             */
            $.ajax({
                type: "GET",
                cache: true,
                url: '/section/store_goodses?auctionId=' + goods_id + '&sellerId=' + seller_id,
                dataType: "html",
                success: function (html) {
                    $('#storeGoodsesList').html(html);
                    if ($('#storeGoodsesList li').length) {
                        $('#storeGoodsesListWrapper').show();
                    }
                }
            });

            /**
             * 为你推荐
             */
            var wrapper = $('#recommendGoodsesList');
            var dataloading = false;
            var loadData = function () {
                if (dataloading) {
                    return;
                }
                dataloading = true;

                var offset = wrapper.find('li').length;
                var limit = 10;
                $.get('/section/search', {
                    keyword: title,
                    offset: offset,
                    limit: limit
                }).then(function (html) {
                    var newList = $('<ul>' + html + '</ul>');
                    var newListLen = $('li.search-item', newList).length;

                    $('li', newList).each(function () {
                        var self = $(this);
                        if ($('#' + self.attr('id')).length) {
                            self.remove();
                        }
                    });
                    $(wrapper).append(newList.html());
                    $("img.lazy").lazyload();

                    if (newListLen < limit) {
                        $(document.body).destroyInfinite();
                        $('#loadmore').hide();
                    }
                }).always(function () {
                    dataloading = false;
                });
            }

            // loadData();
            setTimeout(function () {
                $(document.body).infinite().on("infinite", function () {
                    loadData();
                });
            }, 1200);
        },

        initHome: function () {
            $(".qrcode").on("click", function () {
                $(".code_fixed").show();
            });
            $(".code_fixed .item-bg").on("click", function () {
                $(".code_fixed").hide();
            });

            $('.hash-nav a').click(function () {
                var self = $(this);

                window._hmt && window._hmt.push(['_trackEvent', 'home', self.attr('action') || '']);

                $('.hash-nav a').removeClass('active');

                var activeHref = self.attr('href');
                $('.hash-nav a[href="' + activeHref + '"]').addClass('active');

                $('#search_input').val('');
                setTimeout(function () {
                    refreshData();
                }, 100);
            });

            var hash = location.hash;
            if (hash) {
                hash = hash.split('_')[0];
                var btab = $('.hash-nav a[href="' + hash + '"], .hash-nav a[href="/' + hash + '"]');
                if (btab.length) {
                    $('.hash-nav a').removeClass('active');
                    btab.addClass('active');
                }
            }

            var paramCatIds = getQueryString(location.href, 'catIds');
            var paramSort = getQueryString(location.href, 'sort');
            if (paramCatIds) {
                $('.pinp-navul a.active').removeClass('active');
                $('.pinp-navul a[data-value="' + paramCatIds + '"]').addClass('active');
            }
            if (paramSort) {
                $('.order-wrapper a.active').removeClass('active');
                $('.order-wrapper a[data-value="' + paramSort + '"]').addClass('active');
            }

            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            var wrapper = $('#goodsesList');
            var dataloading = false;
            var dataSearching = false;
            var loadData = function (callback) {
                if (dataloading) {
                    return;
                }
                dataloading = true;

                var keyword = $.trim($('#search_input').val());
                var limit = 20;

                if (dataSearching) {
                    var keyword = $.trim($('#search_input').val());
                    var offset = wrapper.find('li.search-item').length;

                    window._hmt && window._hmt.push(['_trackPageview', '/section/search?keyword=' + keyword + '&offset=' + offset + '&limit=' + limit]);

                    $.get('/section/search', {
                        keyword: keyword,
                        offset: offset,
                        limit: limit
                    }).then(function (html) {
                        var newList = $('<ul>' + html + '</ul>');
                        var newListLen = $('li.search-item', newList).length;

                        $('li', newList).each(function () {
                            var self = $(this);
                            if ($('#' + self.attr('id')).length) {
                                self.remove();
                            }
                        });
                        $(wrapper).append(newList.html());
                        $("img.lazy").lazyload();

                        if (newListLen < limit) {
                            $(document.body).destroyInfinite();
                            $('#loadmore').hide();
                        }
                    }).always(function () {
                        dataloading = false;
                    });

                    return;
                }

                var catIds = $('.pinp-navul a.active').attr('data-value');
                var sort = $('.order-wrapper a.active').attr('data-value');
                var price_start = $('#price_start').val();
                var price_end = $('#price_end').val();
                var offset = wrapper.find('li').length;

                var body = {
                    catIds: catIds,
                    sort: sort,
                    price_start: price_start,
                    price_end: price_end,
                    offset: offset + (parseInt(getQueryString(location.href, 'offset')) || 0),
                    limit: limit,
                    keyword: keyword
                };

                var hash = location.hash;
                if (hash) {
                    body[hash.replace('#', '')] = 1;
                } else {
                    var atab = $('.hash-nav a.active');
                    if (atab.length) {
                        hash = atab.attr('href');
                        body[hash.replace('#', '')] = 1;
                    }
                }

                window._hmt && window._hmt.push(['_trackPageview', '/section/browse?' + $.param(body)]);

                $.post('/section/browse', body).then(function (html) {
                    $(wrapper).append(html);
                    $("img.lazy").lazyload();
                    if (wrapper.find('li').length < offset + limit) {
                        dataloading = false;
                        if (keyword) {
                            dataSearching = true;
                            loadData();
                        } else {
                            $(document.body).destroyInfinite();
                            $('#loadmore').hide();
                        }
                    }
                    if (callback) {
                        callback();
                    }
                }).always(function () {
                    dataloading = false;
                });
            }

            var loadAlimama = function () {
                var keyword = $.trim($('#search_input').val());
                if (keyword && keyword.length > 10) {
                    $.post('/section/alimama_search', {title: keyword}).then(function (html) {
                        $('#alimamaGoodsesList ul').html(html);
                        var len = $('#alimamaGoodsesList li').length;
                        if (len) {
                            $('#alimamaGoodsesList ul').width(len * 125);
                            $('#alimamaGoodsesList').show();
                            new iScroll('alimamaGoodsesList', {
                                scrollbars: false,
                                hScroll: true,
                                hScrollbar: false,
                                vScrollbar: false
                            });
                        }
                    });
                }
            }

            loadData(function () {
                var go = getQueryString(location.href, 'go');
                if (go) {
                    var ele = $('#' + go);
                    if (ele.length) {
                        $("html, body").scrollTop(ele.offset().top - 50);
                    }
                }
            });
            loadAlimama();
            $(document.body).infinite().on("infinite", function () {
                loadData();
            });

            var refreshData = function () {
                if ($('.meishi22').hasClass('grade-w-roll')) {
                    $('.meishi22').removeClass('grade-w-roll');
                }
                wrapper.html('');
                $('#alimamaGoodsesList').hide();

                dataSearching = false;
                loadData();
                loadAlimama();
                $(document.body).destroyInfinite();
                $(document.body).infinite();
            }

            $('.pinp-navul a').click(function () {
                $('.pinp-navul a.active').removeClass('active');
                $(this).addClass('active');

                refreshData();
            });

            $(".orderprice").click(function () {
                if ($('.meishi22').hasClass('grade-w-roll')) {
                    $('.meishi22').removeClass('grade-w-roll');
                } else {
                    $('.meishi22').addClass('grade-w-roll');
                }
            });
            $(".orderby").click(function () {
                $('.order-wrapper a.active').removeClass('active');
                $(this).addClass('active');

                refreshData();
            });

            $('#meishia').on('click', '.jia_xuan a', function () {
                $('.orderprice').attr('data-value', $(this).attr('data-value'));
                $('.order-wrapper a.active').removeClass('active');
                $('.orderprice').addClass('active');

                refreshData();
            }).on('click', '.price_level .price_range_btn', function () {
                $('#price_start').val($(this).attr('cms1') || '');
                $('#price_end').val($(this).attr('cms2') || '');
            });

            $('#cleanval').click(function () {
                $('#price_start').val('');
                $('#price_end').val('');
            });

            $('#confirmPrice').click(function () {
                refreshData();
            });

            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    refreshData();
                    return false;
                }
            });

            $('#search_ok').click(function () {
                refreshData();
                return false;
            });
        },

        initUserEdit: function () {
            $('#save-btn').click(function () {
                if (!$.trim($('#nickname').val())) {
                    return $.toptip('用户昵称不能为空', 'error');
                }
                var telVal = $.trim($('#tel').val());
                if (telVal && !/^1[0-9]{10}$/.test(telVal)) {
                    return $.toptip('手机号格式错误', 'error');
                }
                $.ajax({
                    type: 'POST',
                    url: '/api/public/v1/user/edit',
                    data: $('#user_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '保存失败', 'error');
                    } else {
                        return $.toptip('保存成功', 'success');
                    }
                });
            });

            $('#update-btn').click(function () {
                $.ajax({
                    type: 'POST',
                    url: '/api/public/v1/user/edit_by_wechat'
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '更新失败', 'error');
                    } else {
                        location.reload();
                    }
                });
            });
        },

        initBankEdit: function () {
            $('#save-btn').click(function () {
                if (!$.trim($('#bank_name').val())) {
                    return $.toptip('姓名不能为空', 'error');
                }
                if (!$.trim($('#bank_no').val())) {
                    return $.toptip('账号不能为空', 'error');
                }
                if (!$.trim($('#bank_tel').val())) {
                    return $.toptip('对应手机号不能为空', 'error');
                }
                $.ajax({
                    type: 'POST',
                    url: '/api/public/v1/user/edit',
                    data: $('#bank_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '保存失败', 'error');
                    } else {
                        location.href = '/withdraw_apply';
                    }
                });
            });
        },

        initWithdrawApply: function () {
            $('#apply-btn').click(function () {
                var amount = $.trim($('#amount').val());
                if (!amount) {
                    return $.toptip('提现金额不能为空', 'error');
                }
                if (parseInt(amount) <= 0) {
                    return $.toptip('提现金额输入错误', 'error');
                }
                $.ajax({
                    type: 'POST',
                    url: '/api/front/v1/withdraw/apply',
                    data: $('#withdraw_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '申请失败', 'error');
                    } else {
                        location.href = '/withdraws';
                    }
                });
            });
        },

        initUserCenter: function () {
            $('#myQrcode').click(function () {
                $.showLoading();
                $.ajax({url: '/api/public/v1/user/poster'}).then(function (result) {
                    $.hideLoading();
                    if (!result.success) {
                        return $.toptip(result.message || '获取失败', 'error');
                    } else {
                        try {
                            wx.closeWindow();
                        } catch (e) {
                            console.log(e);
                        }
                    }
                });
            });
        },

        initFinances: function () {
            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    var user_id = $('#user_id').val();
                    $.ajax({url: user_id ? '/user_finances?user_id=' + user_id + '&offset=' + listWrapper.find('li').length : '/finances?offset=' + listWrapper.find('li').length}).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }

            $.ajax({url: '/api/front/v1/orders/orders_frozen?user_id=' + ($('#user_id').val() || '')}).then(function (data) {
                if (data.success) {
                    var data = data.data;
                    $('#frozen_agency_amount').html(data.agency.amount + '/' + data.agency.count);
                    $('#frozen_inviter_agency_amount').html(data.inviter_agency.amount + '/' + data.inviter_agency.count);
                    $('#agency_frozen').show();
                }
            });
        },

        initWithdraws: function () {
            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    var user_id = $('#user_id').val();
                    $.ajax({url: user_id ? '/user_withdraws?user_id=' + user_id + '&offset=' + listWrapper.find('li').length : '/withdraws?offset=' + listWrapper.find('li').length}).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }
        },

        initFansList: function () {
            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    var val = $('#search_input').val();
                    if (val) {
                        location.href = '/fans_list?keyword=' + val;
                    } else {
                        location.href = '/fans_list';
                    }
                    return false;
                }
            });
            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    $.ajax({url: '/fans_list?offset=' + listWrapper.find('li').length}).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }
        },

        initPartnerAgency: function () {
            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    var val = $('#search_input').val();
                    if (val) {
                        location.href = '/partner_agency?keyword=' + val;
                    } else {
                        location.href = '/partner_agency';
                    }
                    return false;
                }
            });
            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            var clipboard;
            var initCopy = function () {
                clipboard = new Clipboard('.clipboard-btn');
                clipboard.on('success', function (e) {
                    e.clearSelection();
                    return $.toptip('成功复制"' + e.text + '"', 'success');
                });
                clipboard.on('error', function (e) {
                    return $.toptip('复制失败, 请手动全选广本复制', 'error');
                });
            }
            initCopy();

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    $.ajax({
                        url: '/partner_agency?offset=' + listWrapper.find('li').length +
                        '&order_by=' + (getQueryString(url, 'order_by') || '')
                    }).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;

                        if (clipboard) {
                            clipboard.destroy();
                        }
                        initCopy();
                    });
                });
            }

            /**
             * 合伙人操作
             */
            $('body').on('click', '.partner-opt a', function () {
                var self = $(this), parentEl = self.parents('.partner-opt');
                var opt = self.attr('opt'), id = parentEl.attr('data-id'), title = self.attr('opt-title');
                if (!opt || !id) {
                    return;
                }
                $.confirm({
                    title: title,
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.post('/api/front/v1/agencys/settle', {opt: opt, id: id}, function (result) {
                            if (result.success) {
                                parentEl.html('<dd class="table-cell vm p10">成功结算, 总佣金' + parseFloat(result.data.settle_amount || 0).toFixed(2) + '元, 代理佣金' + parseFloat(result.data.agency_amount || 0).toFixed(2) + '元, 上级代理佣金' + parseFloat(result.data.inviter_agency_amount || 0).toFixed(2) + '元</dd>');
                                return $.toptip('操作成功', 'success');
                            } else {
                                return $.toptip(result.message || '操作失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });

            $('#allAccountBtn').click(function () {
                var self = $(this);
                $.confirm({
                    title: self.attr('opt-title'),
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.showLoading("执行中...");
                        $.post('/api/front/v1/agencys/batch_settle', function (result) {
                            if (result.success) {
                                location.href = '/partner_settles';
                            } else {
                                $.hideLoading();
                                return $.toptip(result.message || '操作失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });
        },

        initCustomers: function () {
            // 联系客服 - 扫码关注
            $(".contact_con .code").on("click", function () {
                $(".code_fixed").show();
            });
            $(".code_fixed .item-bg").on("click", function () {
                $(".code_fixed").hide();
            });
        },

        initSuggestions: function () {
            // 建议反馈
            $('#suggestion-btn').click(function () {
                var content = $.trim($('#content').val());
                if (!content) {
                    return $.toptip('内容不能为空', 'error');
                }
                $.ajax({
                    type: 'POST',
                    url: '/api/front/v1/suggestion/save',
                    data: $('#suggestion_form').serialize()
                }).then(function (result) {
                    if (!result.success) {
                        return $.toptip(result.message || '提交失败', 'error');
                    } else {
                        $.alert("提交成功", function () {
                            location.href = '/user_center';
                        });
                    }
                });
            });
        },

        initGoodsesSearchs: function () {
            var wrapper = $('#goodsesList');
            var dataloading = false;
            var loadData = function () {
                if (dataloading) {
                    return;
                }
                dataloading = true;

                var offset = wrapper.find('li').length;
                var limit = 20;
                $.get('/section/browse_search', {
                    offset: offset,
                    limit: limit
                }).then(function (html) {
                    $(wrapper).append(html);
                    $("img.lazy").lazyload();

                    if (wrapper.find('li').length < offset + limit) {
                        $(document.body).destroyInfinite();
                        $('#loadmore').hide();

                        if (!wrapper.find('li').length) {
                            $('#nothing').show();
                        } else {
                            $('#nothing').show().html('<span class="mt10 fs14 col9">没有更多记录了！</span>');
                        }
                    }
                }).always(function () {
                    dataloading = false;
                });
            }

            loadData();
            $(document.body).infinite().on("infinite", function () {
                loadData();
            });
        },

        initGoodsesViews: function () {
            var wrapper = $('#goodsesList');
            var dataloading = false;
            var loadData = function () {
                if (dataloading) {
                    return;
                }
                dataloading = true;

                var offset = wrapper.find('li').length;
                var limit = 20;
                $.get('/section/browse_views', {
                    offset: offset,
                    limit: limit
                }).then(function (html) {
                    $(wrapper).append(html);
                    $("img.lazy").lazyload();

                    if (wrapper.find('li').length < offset + limit) {
                        $(document.body).destroyInfinite();
                        $('#loadmore').hide();

                        if (!wrapper.find('li').length) {
                            $('#nothing').show();
                        } else {
                            $('#nothing').show().html('<span class="mt10 fs14 col9">没有更多记录了！</span>');
                        }
                    }
                }).always(function () {
                    dataloading = false;
                });
            }

            loadData();
            $(document.body).infinite().on("infinite", function () {
                loadData();
            });
        },

        initMyOrders: function () {
            $('body').on("click", ".qrcode", function () {
                $(".code_fixed").show();
            });
            $(".code_fixed .item-bg").on("click", function () {
                $(".code_fixed").hide();
            });

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    $.ajax({url: '/my_orders?offset=' + listWrapper.find('li').length}).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }

            /**
             * 用户操作
             */
            $('body').on('click', '.user-opt a', function () {
                var self = $(this), parentEl = self.parents('.user-opt');
                var opt = self.attr('opt'), id = parentEl.attr('data-id'), title = self.attr('opt-title');
                if (!opt || !id) {
                    return;
                }
                $.confirm({
                    title: title,
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.post('/api/front/v1/user_orders/operate', {opt: opt, id: id}, function (result) {
                            if (result.success) {
                                self.parents('li').remove();
                                return $.toptip('删除成功', 'success');
                            } else {
                                return $.toptip(result.message || '删除失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });
        },

        initFansOrders: function () {
            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    var val = $('#search_input').val();
                    if (val) {
                        location.href = '/fans_orders?taobaoTradeParentId=' + val;
                    } else {
                        location.href = '/fans_orders';
                    }
                    return false;
                }
            });
            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            $.ajax({url: '/api/front/v1/orders/orders_analyse?agency_id=' + $('#agency_id').val()}).then(function (data) {
                if (data.success) {
                    var data = data.data;
                    $('#all_amount').html(data.all_amount.amount + '/' + data.all_amount.count);
                    $('#pending_settle').html(data.pending_settle.amount + '/' + data.pending_settle.count);
                    $('#pending_account').html(data.pending_account.amount + '/' + data.pending_account.count);
                }
            });

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    var status = $('#status-filter a.active').attr('data-value');

                    $.ajax({url: '/fans_orders?status=' + status + '&offset=' + listWrapper.find('li').length}).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }
        },

        initPartnerOrders: function () {
            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    var val = $('#search_input').val();
                    if (val) {
                        location.href = '/partner_orders?keyword=' + val + '&type=' + getQueryString(location.href, 'type');
                    } else {
                        location.href = '/partner_orders?type=' + getQueryString(location.href, 'type');
                    }
                    return false;
                }
            });
            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    var status = $('#status-filter a.active').attr('data-value');
                    var url = location.href;
                    $.ajax({
                        url: '/partner_orders?status=' + status + '&offset=' + listWrapper.find('li').length +
                        '&mediumId=' + (getQueryString(url, 'mediumId') || '') +
                        '&keyword=' + (getQueryString(url, 'keyword') || '') +
                        '&user_id=' + (getQueryString(url, 'user_id') || '') +
                        '&agency_id=' + (getQueryString(url, 'agency_id') || '') +
                        '&agency_settle_id=' + (getQueryString(url, 'agency_settle_id') || '') +
                        '&type=' + getQueryString(location.href, 'type')
                    }).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }

            /**
             * 合伙人操作
             */
            $('body').on('click', '.partner-opt a', function () {
                var self = $(this), parentEl = self.parents('.partner-opt');
                var opt = self.attr('opt'), id = parentEl.attr('data-id'), title = self.attr('opt-title');
                if (!opt || !id) {
                    return;
                }
                $.confirm({
                    title: title,
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.post('/api/front/v1/orders/operate', {opt: opt, id: id}, function (result) {
                            if (result.success) {
                                parentEl.html('<dd class="table-cell vm p10">' + title + '操作成功, 刷新后对该订单进行其它操作</dd>')
                                return $.toptip('操作成功', 'success');
                            } else {
                                return $.toptip(result.message || '操作失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });
        },

        initPartnerSettles: function () {
            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    $.ajax({url: '/partner_settles?offset=' + listWrapper.find('li').length}).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }

            /**
             * 合伙人操作
             */
            $('body').on('click', '.partner-opt a', function () {
                var self = $(this), parentEl = self.parents('.partner-opt');
                var opt = self.attr('opt'), id = parentEl.attr('data-id'), title = self.attr('opt-title');
                if (!opt || !id) {
                    return;
                }
                $.confirm({
                    title: title,
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.post('/api/front/v1/settles/handle', {opt: opt, id: id}, function (result) {
                            if (result.success) {
                                parentEl.html('<dd class="table-cell vm p10">' + title + '成功</dd>');
                                return $.toptip('操作成功', 'success');
                            } else {
                                return $.toptip(result.message || '操作失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });

            $('.allAccountBtn').click(function () {
                var self = $(this);
                $.confirm({
                    title: self.attr('opt-title'),
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.showLoading("执行中...");
                        $.post('/api/front/v1/settles/batch_handle', {opt: self.attr('opt')}, function (result) {
                            if (result.success) {
                                location.reload();
                            } else {
                                $.hideLoading();
                                return $.toptip(result.message || '操作失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });
        },

        initPartnerWithdraws: function () {
            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    var val = $('#search_input').val();
                    if (val) {
                        location.href = '/partner_withdraws?keyword=' + val;
                    } else {
                        location.href = '/partner_withdraws';
                    }
                    return false;
                }
            });
            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            var clipboard;
            var initCopy = function () {
                clipboard = new Clipboard('.clipboard-btn');
                clipboard.on('success', function (e) {
                    e.clearSelection();
                    return $.toptip('成功复制"' + e.text + '"', 'success');
                });
                clipboard.on('error', function (e) {
                    return $.toptip('复制失败, 请手动全选广本复制', 'error');
                });
            }
            initCopy();

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    $.ajax({
                        url: '/partner_withdraws?offset=' + listWrapper.find('li').length +
                        '&keyword=' + (getQueryString(url, 'keyword') || '') +
                        '&status=' + (getQueryString(url, 'status') || '')
                    }).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;

                        if (clipboard) {
                            clipboard.destroy();
                        }
                        initCopy();
                    });
                });
            }

            /**
             * 合伙人操作
             */
            $('body').on('click', '.partner-opt a', function () {
                var self = $(this), parentEl = self.parents('.partner-opt');
                var status = self.attr('status'), id = parentEl.attr('data-id'), title = self.attr('opt-title');
                if (!status || !id) {
                    return;
                }
                $.confirm({
                    title: title,
                    text: self.attr('opt-desc'),
                    onOK: function () {
                        $.post('/api/front/v1/withdraw/status', {status: status, id: id}, function (result) {
                            if (result.success) {
                                parentEl.html('<dd class="table-cell vm p10">' + title + '成功</dd>');
                                return $.toptip('操作成功', 'success');
                            } else {
                                return $.toptip(result.message || '操作失败', 'error');
                            }
                        }, 'json');
                    }
                });
            });
        },

        initPartnerUsers: function () {
            $('#search_input').keypress(function (e) {
                var key = e.which;
                if (key == 13) {
                    var val = $('#search_input').val();
                    if (val) {
                        location.href = '/partner_users?keyword=' + val;
                    } else {
                        location.href = '/partner_users';
                    }
                    return false;
                }
            });
            if ($('#search_input').val()) {
                $('#search_text')[0].click();
            }

            if ($('.loadmore-wrapper .weui-infinite-scroll').length) {
                var loading = false;
                $(document.body).infinite().on("infinite", function () {
                    if (loading) return;
                    loading = true;

                    var listWrapper = $('.list-wrapper'), loadmoreWrapper = $('.loadmore-wrapper');
                    var url = location.href;
                    $.ajax({
                        url: '/partner_users?offset=' + listWrapper.find('li').length +
                        '&keyword=' + (getQueryString(url, 'keyword') || '') +
                        '&order_by=' + (getQueryString(url, 'order_by') || '') +
                        '&agency_id=' + (getQueryString(url, 'agency_id') || '') +
                        '&inviter_id=' + (getQueryString(url, 'inviter_id') || '')
                    }).then(function (html) {
                        var dom = $(html);
                        listWrapper.append(dom.find('.list-wrapper').html());
                        loadmoreWrapper.html(dom.find('.loadmore-wrapper').html());
                        if (!$('.loadmore-wrapper .weui-infinite-scroll').length) {
                            $(document.body).destroyInfinite()
                        }
                        loading = false;
                    });
                });
            }
        }

    }

    var url = location.href;
    if (url.indexOf('/detail') != -1) {
        taoke.initDetail();
    } else if (url.indexOf('/login') != -1) {
        taoke.initLogin();
    } else if (url.indexOf('/register') != -1) {
        taoke.initRegister();
    } else if (url.indexOf('/forgot') != -1) {
        taoke.initForgot();
    } else if (url.indexOf('/user_edit') != -1) {
        taoke.initUserEdit();
    } else if (url.indexOf('/bank_edit') != -1) {
        taoke.initBankEdit();
    } else if (url.indexOf('/withdraw_apply') != -1) {
        taoke.initWithdrawApply();
    } else if (url.indexOf('/finances') != -1 || url.indexOf('/user_finances') != -1) {
        taoke.initFinances();
    } else if (url.indexOf('/withdraws') != -1 || url.indexOf('/user_withdraws') != -1) {
        taoke.initWithdraws();
    } else if (url.indexOf('/user_center') != -1) {
        taoke.initUserCenter();
    } else if (url.indexOf('/fans_list') != -1) {
        taoke.initFansList();
    } else if (url.indexOf('/customers') != -1) {
        taoke.initCustomers();
    } else if (url.indexOf('/goodses_searchs') != -1) {
        taoke.initGoodsesSearchs();
    } else if (url.indexOf('/goodses_views') != -1) {
        taoke.initGoodsesViews();
    } else if (url.indexOf('/customers') != -1) {
        taoke.initCustomers();
    } else if (url.indexOf('/suggestions') != -1) {
        taoke.initSuggestions();
    } else if (url.indexOf('/my_orders') != -1) {
        taoke.initMyOrders();
    } else if (url.indexOf('/last_visitors') != -1) {

    } else if (url.indexOf('/fans_orders') != -1) {
        taoke.initFansOrders();
    } else if (url.indexOf('/partner_orders') != -1) {
        taoke.initPartnerOrders();
    } else if (url.indexOf('/partner_agency') != -1) {
        taoke.initPartnerAgency();
    } else if (url.indexOf('/partner_settles') != -1) {
        taoke.initPartnerSettles();
    } else if (url.indexOf('/partner_withdraws') != -1) {
        taoke.initPartnerWithdraws();
    } else if (url.indexOf('/partner_users') != -1) {
        taoke.initPartnerUsers();
    } else {
        taoke.initHome();
    }
});